package com.nuc.thread.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author 诗酒趁年华
 * @version 1.0.0
 * @Description 自定义锁:不可重入
 * @createTime 2021年08月14日 12:03:00
 */
public class MyLock implements Lock {

    //自定义同步器
    class MySync extends AbstractQueuedSynchronizer{

        protected MySync() {
            super();
        }

        /**
         * 尝试加锁
         * @param arg
         * @return
         */
        @Override
        protected boolean tryAcquire(int arg) {
            //加锁：修改state为1，并设置owner为当前线程
            if (compareAndSetState(0,1)){
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        /**
         * 尝试解锁
         * @param arg
         * @return
         */
        @Override
        protected boolean tryRelease(int arg) {
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        @Override
        protected int tryAcquireShared(int arg) {
            return super.tryAcquireShared(arg);
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            return super.tryReleaseShared(arg);
        }

        /**
         * 是否持有独占锁
         * @return
         */
        @Override
        protected boolean isHeldExclusively() {
            return getState()==1;
        }

        public Condition newCondition(){
            return new ConditionObject();
        }

        @Override
        public String toString() {
            return super.toString();
        }
    }

    MySync mySync = new MySync();

    /**
     * 加锁
     */
    @Override
    public void lock() {
        mySync.acquire(1);
    }

    /**
     * 加锁：可打断
     * @throws InterruptedException
     */
    @Override
    public void lockInterruptibly() throws InterruptedException {
        mySync.acquireInterruptibly(1);
    }

    /**
     * 尝试加锁
     * @return
     */
    @Override
    public boolean tryLock() {
        return mySync.tryAcquire(1);
    }

    /**
     * 带超时的加锁
     * @param time
     * @param unit
     * @return
     * @throws InterruptedException
     */
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return mySync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        mySync.release(1);
    }

    @Override
    public Condition newCondition() {
        return mySync.newCondition();
    }
}
